package com.crm.system.controller.customerManager;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DataResponse;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.cluePoolManager.ClueVisitRecord;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.customerManager.*;
import com.crm.model.entity.orderManager.CustomerProductOrder;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.customerManager.AnalyseCustomerQO;
import com.crm.model.qo.customerManager.CustomerAddQO;
import com.crm.model.qo.customerManager.CustomerQO;
import com.crm.model.qo.customerManager.MoveCustomerQO;
import com.crm.model.vo.cluePoolManager.ClueFollowVO;
import com.crm.model.vo.contactManager.ContactMyVO;
import com.crm.model.vo.contactManager.IndustryAreaVO;
import com.crm.model.vo.customerManager.*;
import com.crm.model.vo.opportunityManager.OpportunityCustomerVO;
import com.crm.model.vo.returnMoney.CustFinanceProductOderVO;
import com.crm.redis.service.customerManager.CustomerRedisService;
import com.crm.system.service.contactManager.ContactService;
import com.crm.system.service.customerManager.CustomerContactPersonService;
import com.crm.system.service.customerManager.CustomerRelationService;
import com.crm.system.service.customerManager.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ Author ：baijian
 * @ Date   ：2021/1/18 15:53
 */
@RestController
@RequestMapping("/customerRelation")
@Slf4j
public class CustomerRelationController {

    @Value("${esurl}")
    public String ESurl;

    @Autowired
    CustomerRelationService customerRelationService;

    @Autowired
    CustomerService customerService;

    /**
     * 查询客户关联
     * @param customerId 客户id
     * @return
     */
    @PostMapping("/selectCustomerRelationList")
    public DataResponse selectCustomerRelationList(HttpServletRequest request,
                                                             @RequestParam(value = "customerId", required = true) String customerId
    ) {
        try {
            List<CustomerRelation> list = customerRelationService.selectCustomerRelationList(customerId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), list);
        } catch (Exception e) {
            log.error("customerRelation selectCustomerRelationList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 新增客户关联
     * @param customerRelation
     * @return
     */
    @PostMapping("/addCustomerRelation")
    public DataResponse addCustomerRelation(@RequestBody CustomerRelation customerRelation) {
        try {
            String result = customerRelationService.addCustomerRelation(customerRelation);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),result);
        } catch (Exception e) {
            log.error("customerRelation addCustomerRelation error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 删除客户关联
     * @param customerRelation
     * @return
     */
    @PostMapping("/deleteCustomerRelation")
    public DataResponse deleteCustomerRelation(@RequestBody CustomerRelation customerRelation) {
        try {
            Boolean result = customerRelationService.deleteCustomerRelation(customerRelation);
            if (result) {
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
            }
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        } catch (Exception e) {
            log.error("customerRelation deleteCustomerRelation error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 修改曾用名
     * @param customerRelation
     * @return
     */
    @PostMapping("/updateNameUsedBefore")
    public DataResponse updateNameUsedBefore(@RequestBody CustomerRelation customerRelation) {
        try {
            Boolean result = customerRelationService.updateNameUsedBefore(customerRelation);
            if (result) {
                Customer es = customerService.selectCustomerById(customerRelation.getCustomerId());
                syncES(es,es.getAccountId(),"客户详情-客户曾用名-客气切换名称");
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
            }
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        } catch (Exception e) {
            log.error("customerRelation updateNameUsedBefore error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 曾用名写入信用代码
     * @return
     */
    @PostMapping("/updateCustomerRelation")
    public DataResponse updateNameUsedBefore() {
        try {
            Boolean result = customerRelationService.updateCustomerRelation();
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        } catch (Exception e) {
            log.error("customerRelation updateCustomerRelation error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }



    /**
     * 客户关联审核列表
     * @param pageIndex 页码
     * @param pageSize 条数
     * @param sortName 分组字段
     * @param sortOrder 排序
     * @param dateType 全部  all  本月 thisMonth 本周 thisWeek
     * @param customerName 客户名称
     * @return
     */
    @PostMapping("/examineCustomerRelationList")
    public DataResponse examineCustomerRelationList(HttpServletRequest request,
                                         @RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                         @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                         @RequestParam(value = "sortName", required = false) String sortName,//排序列名字
                                         @RequestParam(value = "sortOrder", required = false) String sortOrder,//排序规则(asc/desc)
                                         @RequestParam(value = "dateType", required = false) String dateType,
                                         @RequestParam(value = "customerName", required = false) String customerName


    ) {
        try {
            DhPageInfo<CustomerRelationVO> customerVOList = customerRelationService.examineCustomerRelationList(pageIndex, pageSize, sortName, sortOrder,dateType,customerName);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), customerVOList);
        } catch (Exception e) {
            log.error("customerRelation examineCustomerRelationList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 客户核验关联信息
     * @param customerRelation
     * @return
     */
    @PostMapping("/aexamineRelation")
    public DataResponse aexamineRelation(@RequestBody CustomerRelation customerRelation) {
        try {
            Boolean result = customerRelationService.aexamineRelation(customerRelation);
            if (result) {
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
            }
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        } catch (Exception e) {
            log.error("customerRelation aexamineRelation error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    private void syncES(Customer customer,String accountId,String msg) {

        String token = getToken(accountId,msg);

        Map<String, Object> parMap = transBean2Map(customer);
        parMap.put("authorization",token);
        parMap.put("key",accountId);
        try {
            String result = HttpUtil.post(ESurl+"/cutomer/insertOrUpdate",parMap);
            log.info(msg+"----"+result);
        } catch (HttpException e) {
            log.info(msg+"ES同步失败");
        }
    }

    private String getToken(String accountId, String msg) {
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("accountId", accountId);
        try {
            return HttpUtil.post(ESurl+"/token/initToken",tokenMap);
        } catch (Exception e) {
            log.info(msg+"获取token失败");
        }
        return null;
    }


    /**
     * 对象装换map
     * @param obj
     * @return
     */
    private static Map<String, Object> transBean2Map(Object obj) {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // 得到property对应的getter方法
                Method getter = property.getReadMethod();
                Object value = getter.invoke(obj);
                map.put(key, value);

            }
        } catch (Exception e) {
            System.out.println("transBean2Map Error " + e);
        }
        return map;
    }



}
